/*******************************************************************************
* BSP
* ===
*
* The mainline of any test or demo needs to be devoid of hardware-specific
* functionality.  Instead general functions like `led_on()` or `start_adc()` or
* the like need to be used and the hardware implementation of these defined here
* in the BSP file.
*
* The absolute first thing that has to be provided is printf support so that
* program and demo outputs can be seen either on the console or on a serial port
* as appropriate.
*******************************************************************************/

#include <stdbool.h>
#include <stdio.h>

#include "bsp.h"

#include "stm32l4xx_hal.h"

/***************************************
* Utility macros and constants.
***************************************/

#define STEP_DELAY_MS                    (uint32_t)(50)
#define TICK_COUNT_MAX                   (uint32_t)(0xFFFFFF)
#define TICK_COUNT_VALUE                 (SysTick->VAL)

#define VCP_TX_Pin GPIO_PIN_2
#define VCP_TX_GPIO_Port GPIOA
#define VCP_RX_Pin GPIO_PIN_15
#define VCP_RX_GPIO_Port GPIOA

/***************************************
* Static helper functions
***************************************/

static void bsp_periph_clock_config(void);
static void bsp_system_clock_config(void);
static void bsp_printf_uart_init(void);

/***************************************
* Global system-wide variables
***************************************/

volatile uint64_t systick_counter;

/***************************************
* Local static variables
***************************************/

static UART_HandleTypeDef printf_uart;

/***************************************
* BSP functions for AT32F403AVG
***************************************/

void bsp_initialize()
{
    HAL_Init();

    bsp_system_clock_config();
    bsp_periph_clock_config();
    bsp_printf_uart_init();
}

/***************************************
* Static function implementations
***************************************/

static void bsp_periph_clock_config(void)
{
    RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART2;
    PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1;

    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { while (true) {} }

    __HAL_RCC_SYSCFG_CLK_ENABLE();
    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_RCC_USART2_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();
}

static void bsp_system_clock_config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) { while (true) {} }

    HAL_PWR_EnableBkUpAccess();
    __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);


    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI;
    RCC_OscInitStruct.LSEState = RCC_LSE_ON;
    RCC_OscInitStruct.MSIState = RCC_MSI_ON;
    RCC_OscInitStruct.MSICalibrationValue = 0;
    RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
    RCC_OscInitStruct.PLL.PLLM = 1;
    RCC_OscInitStruct.PLL.PLLN = 40;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
    RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
    RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;

    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { while (true) {} }

    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { while (true) {} }
}

void bsp_printf_uart_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    GPIO_InitStruct.Pin = VCP_TX_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART2;
    HAL_GPIO_Init(VCP_TX_GPIO_Port, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = VCP_RX_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF3_USART2;
    HAL_GPIO_Init(VCP_RX_GPIO_Port, &GPIO_InitStruct);

    printf_uart.Instance = USART2;
    printf_uart.Init.BaudRate = 115200;
    printf_uart.Init.WordLength = UART_WORDLENGTH_8B;
    printf_uart.Init.StopBits = UART_STOPBITS_1;
    printf_uart.Init.Parity = UART_PARITY_NONE;
    printf_uart.Init.Mode = UART_MODE_TX_RX;
    printf_uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    printf_uart.Init.OverSampling = UART_OVERSAMPLING_16;
    printf_uart.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
    printf_uart.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;

    if (HAL_UART_Init(&printf_uart) != HAL_OK) { while (true) {} }
}

/***************************************
* printf support
***************************************/

#if defined (__GNUC__) && !defined (__clang__)
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif

static const uint8_t cr = '\r';

/**
  * @brief  retargets the c library printf function to the usart.
  * @param  none
  * @retval none
  */
PUTCHAR_PROTOTYPE
{
#if !defined (__GNUC__) || defined (__clang__)
    UNUSED(f);
#endif

    while (!__HAL_UART_GET_FLAG(&printf_uart, UART_FLAG_TXE));

    if (ch == '\n')
    {
        HAL_UART_Transmit(&printf_uart, (uint8_t *)&cr, 1, HAL_MAX_DELAY);
    }

    HAL_UART_Transmit(&printf_uart, (uint8_t *)&ch, 1, HAL_MAX_DELAY);

    while (!__HAL_UART_GET_FLAG(&printf_uart, UART_FLAG_TC));

    return ch;
}

#if (defined (__GNUC__) && !defined (__clang__)) || (defined (__ICCARM__))
#if defined (__GNUC__) && !defined (__clang__)
int _write(int fd, char *pbuffer, int size)
#elif defined ( __ICCARM__ )
#pragma module_name = "?__write"
int __write(int fd, char *pbuffer, int size)
#endif
{
    UNUSED(fd);

    for (int i = 0; i < size; i++)
    {
        if (pbuffer[i] == '\n')
        {
            HAL_UART_Transmit(&printf_uart, (uint8_t *)&cr, 1, HAL_MAX_DELAY);
        }

        HAL_UART_Transmit(&printf_uart, (uint8_t *)&pbuffer[i], 1, HAL_MAX_DELAY);
    }

    return size;
}
#endif

/***************************************
* ISRs
***************************************/

void NMI_Handler(void)
{
}

void HardFault_Handler(void)
{
    while (1) { }
}

void MemManage_Handler(void)
{
    while (1) { }
}

void BusFault_Handler(void)
{
    while (1) { }
}

void UsageFault_Handler(void)
{
    while (1) { }
}

void SVC_Handler(void)
{
}

void DebugMon_Handler(void)
{
}

void PendSV_Handler(void)
{
}

void SysTick_Handler(void)
{
    HAL_IncTick();
    systick_counter++;
}
